package org.tang.springcloudvv.util;


import javax.servlet.http.HttpServletRequest;

public class IPUtil {
    
    
    /**
     * 获取客户端请求的ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        try{
            StringBuffer sb = new StringBuffer();
            sb.append("getIP_in_k8s:"+request.getHeader("X-Real-IP")+";");
            sb.append(""+request.getHeader("X-Forwarded-For")+";");
            sb.append(""+request.getRemoteAddr()+";");

            String ip = request.getHeader("X-Real-IP");
            if (ip != null && !ip.equals("") && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
            ip = request.getHeader("X-Forwarded-For");

            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            if (ip != null && !ip.equals("") && !"unknown".equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个IP值，第一个为真实IP。
                int index = ip.indexOf(',');
                if (index != -1) {
                    return ip.substring(0, index);
                } else {
                    return ip;
                }
            } else {
                return request.getRemoteAddr();
            }
        }
        catch(Exception e)
        {
            return "getIpError";
        }
    }
    //获取Ip的前两节
    public static String getPrefix2(String ip)
    {
        int index = ip.indexOf(".");
        index = ip.indexOf(".",index+1);
        return ip.substring(0,index);
    }
    
}
